package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * JDBC java database connectivity    java数据库链接
 */
public class JDBCDemo1 {
    public static void main(String[] args) throws Exception {
        /*
            大致流程
            1:加载驱动
            2:使用DriverManager建立链接->Connection
            3:通过Connection创建语句执行对象->Statement
            4:通过Statement执行SQL语句
            5:遍历结果集(前提是步骤4执行的是DQL语句，SELECT语句)
            6:关闭链接
         */
        //1
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2
        Connection conn = DriverManager.getConnection(
                //jdbc:mysql://数据库地址:端口/数据库名?一堆固定参数
                "jdbc:mysql://localhost:3306/tedu?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true",
                "root",
                "root"
        );
        System.out.println("与数据库建立链接!");
        //3
        Statement statement = conn.createStatement();
        /*
            4
            CREATE TABLE userinfo(
                id INT PRIMARY KEY AUTO_INCREMENT,
                username VARCHAR(32),
                password VARCHAR(32),
                nickname VARCHAR(32),
                age INT(3)
            )
         */
        String sql = "CREATE TABLE userinfo(" +
                "                id INT PRIMARY KEY AUTO_INCREMENT," +
                "                username VARCHAR(32)," +
                "                password VARCHAR(32)," +
                "                nickname VARCHAR(32)," +
                "                age INT(3)" +
                "            ) ";
        /*
            boolean execute(String sql)
            用于执行sql语句，如果执行后产生了查询结果集会返回true
            如果执行语句有错误会抛出异常。由于执行DML,DQL有专门提供方法，因此
            该方法通常仅用来执行DDL
         */
        statement.execute(sql);
        System.out.println("表创建完毕");

        //关闭链接
        conn.close();

    }
}
